package com.smartClassroom.content.service.Impl;

import com.smartClassroom.content.mapper.CourseCategoryMapper;
import com.smartClassroom.content.model.dto.CourseCategoryTreeDto;
import com.smartClassroom.content.service.CourseCategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class CourseCategoryServiceImpl implements CourseCategoryService {

    @Autowired
    private CourseCategoryMapper courseCategoryMapper;
    @Override
    public List<CourseCategoryTreeDto> queryTreeNodes(String id) {
        List<CourseCategoryTreeDto> courseCategories = courseCategoryMapper.selectTreeNodes(id);

        //便于找父节点
        Map<String, CourseCategoryTreeDto> map = courseCategories.stream().filter(item -> !item.getId().equals(id)).collect(Collectors.toMap(key -> key.getId(), value -> value, (key1, key2) -> key2));

        List<CourseCategoryTreeDto> result = new ArrayList<>();
        courseCategories.stream().filter(item -> !item.getId().equals(id)).forEach(item->{
            if (item.getParentid().equals(id)){
                result.add(item);
            }else {
                //寻找父节点
                CourseCategoryTreeDto categoryParent = map.get(item.getParentid());
                if (categoryParent!=null){
                    if (categoryParent.getChildrenTreeNodes()==null){
                        categoryParent.setChildrenTreeNodes(new ArrayList<CourseCategoryTreeDto>());
                    }else {
                        categoryParent.getChildrenTreeNodes().add(item);
                    }
                }
            }
        });
        return result;
    }
}
